/**
 * Created by zhulousheng on 2018/4/28.
 */
import axios from 'axios'
// import store from '../store'
import { Message } from 'iview'

var ajax = function (params) {
  // store.commit('SET_LOADING', true)
  var fetchObj
  let isLogin = params.islogin === undefined ? false : params.islogin
  // let isSubmit = params.isSubmit === undefined ? false : params.isSubmit
  if (isLogin){
    if (params.type === 'post' || params.type === 'POST') {
      let param = Object.assign({}, params.data)
      fetchObj = axios.post(
        params.url,
        param,
        {headers:
            {}
        }
      )
    } else if (params.type === 'get' || params.type === 'GET') {
      let param = Object.assign({}, params.data)
      let paramStr = ''
      for (var key in param) {
        paramStr += key + '=' + param[key] + '&'
      }
      paramStr = paramStr.substring(0, paramStr.length - 1)
      fetchObj = axios.get(
        params.url += '?' + paramStr,
        {headers:
            {}
        }
      )
    }
  } else {
    let token = {token: sessionStorage.getItem('token')?JSON.parse(sessionStorage.getItem('token')):''}
    let loginId = {loginId: sessionStorage.getItem('id')?JSON.parse(sessionStorage.getItem('id')):''}
    let client = {client: "manager"};
    if (params.type === 'post' || params.type === 'POST') {
      let param = Object.assign({}, params.data, token, loginId, client)
      fetchObj = axios.post(
        params.url,
        param,
        {headers:
            {}
        }
      )
    } else if (params.type === 'get' || params.type === 'GET') {
      let param = Object.assign({}, params.data, token, loginId, client)
      let paramStr = ''
      for (var key in param) {
        paramStr += key + '=' + param[key] + '&'
      }
      paramStr = paramStr.substring(0, paramStr.length - 1)
      fetchObj = axios.get(
        params.url += '?' + paramStr,
        {headers:
            {}
        }
      )
    }
  }
  fetchObj.then(function (res) {
    // store.commit('SET_LOADING', false)
    if (res.status === 200) {
      let data = res.data
      if(data.code == 200) {
        params.success(data)
      } else {
        params.error(data)
      }
    } else {
      Message.error('系统错误，请联系管理员');
    }
  }).catch(error => {
    // 网络错误
    Message.error('网络连接错误');
    console.log(error)
  })
}

export {
  ajax
}

